#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"

//可用于存储任何返回值为void且无参数的可调用对象
using task_t=std::function<void()>;

class MessageRout
{
private:
    bool IsExists(InetAddr addr)
    {
        for (auto a : _online_user)
        {
            if (a.IP() == addr.IP() && a.Port() == addr.Port())
            {
                return true;
            }
        }

        return false;
    }

public:
    MessageRout()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    void AddUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        if (IsExists(addr))
        {
            return;
        }
        _online_user.push_back(addr);
    }

    void DelUser(InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if ((*iter).IP() == addr.IP() && (*iter).Port() == addr.Port())
            {
                _online_user.erase(iter);
            }
        }
    }

    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard lockguard(&_mutex);
        // 将信息转发给所有在线用户
        for (auto u : _online_user)
        {
            std::string send_message = "\n[" + who.IP() + ":" + std::to_string(who.Port()) + "]# " + message + "\n";
            struct sockaddr_in clientaddr = u.Addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }

    void Route(int sockfd, std::string message, InetAddr who)
    {
        // 1.我们任务，用户首次发消息，不仅发消息，还要讲自己插入到用户队伍里
        AddUser(who);

        // 1.1如果客户端要退出
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        // 2. 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(&MessageRout::RouteHelper,this,sockfd,message,who);
        //创建线程单例，并将t插入线程池
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};